<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 飞鱼
 */
class FeiyuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['appid'] = $this->config['mch_id'];
        $data['orderNo'] = $return['orderid'];
        $data['dateTime'] = date("YmdHis",time());
        switch($this->config['paytype']) {
            //微信
            case 1:
                $data['payType'] = 'SCANPAY_WEIXIN';
                break;
            //支付宝
            case 3:
                $data['payType'] = 'SCANPAY_ALIPAY';
                break;
            //支付宝H5
            case 4:
                $data['payType'] = 'SCANPAY_ALIPAY';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['amount'] = $return['amount']*100;
        $data['productName'] = 'zf';
        $data['asynNotifyUrl'] = $return['notifyurl'];
        $data['returnUrl'] = $return['callbackurl'];

        krsort($data);

        $str = '';
        foreach($data as $k=>$v){
            $str .= $v;
        }

        $name = iconv('UTF-8','GBK',$str);
        $utf8Str = mb_convert_encoding(strtoupper(md5($name)), "UTF-8");

        $sign = strtoupper(hash_hmac("sha1", $utf8Str, $this->config['signkey']));
        $data['sign'] = $sign;

        $res = curl($this->config['gateway'], httpstr($data));
        $res = json_decode($res, true);
        $res['data'] = json_decode($res['data'],true);
        $code = $res['data']['payUrl'];

        if(!$code){
            if($res['message']){
                $this->showmessage($res['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        if(in_array($this->config['paytype'],[3,4,17,18])){
            header("Location:{$code}"); exit;
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        $this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //微信
            case 1:
                if($isMobile){
                    $this->display("WeiXin/weixinwap");
                }else{
                    $this->display("WeiXin/weixin");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = file_get_contents('php://input');

        //$p = "data=%7B%22amount%22%3A10%2C%22appId%22%3A%229969ed418ae44d49bca97f6573784b2f%22%2C%22orderNo%22%3A%222018121517495715495%22%2C%22payTrxNo%22%3A%220001692018121517495715495%22%2C%22resultcode%22%3A%220000%22%2C%22resultmessage%22%3A%22%E4%BA%A4%E6%98%93%E6%88%90%E5%8A%9F%22%2C%22paySign%22%3A%22B18C6B9671BEE9221CEFC465A414B2464048B3FC%22%2C%22version%22%3A1%7D";

        parse_str($p, $p);

        if(!$p || empty($p)){
            echo '';exit;
        }

        $p = json_decode($p['data'], true);

        if(!$p || empty($p)){
            exit("wrong");
        }

        /**
         * Array
        (
        [amount] => 10
        [appId] => 9969ed418ae44d49bca97f6573784b2f
        [orderNo] => 2018121517495715495
        [payTrxNo] => 0001692018121517495715495
        [resultcode] => 0000
        [resultmessage] => 交易成功
        [paySign] => B18C6B9671BEE9221CEFC465A414B2464048B3FC
        [version] => 1
        )
         */

        //获取订单信息
        $orderid = $p['orderNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['payTrxNo']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['paySign'];
        unset($p['paySign']);

        krsort($p);

        $str = '';
        foreach($p as $k=>$v){
            $str .= $v;
        }

        $name = iconv('UTF-8','GBK',$str);
        $utf8Str = mb_convert_encoding(strtoupper(md5($name)), "UTF-8");

        $sign2 = strtoupper(hash_hmac("sha1", $utf8Str, $this->config['signkey']));

        if($sign !== $sign2){
            echo 'sign wrong'; exit;
        }

        if($p['resultcode'] !== '0000'){
            echo 'pay fail'; exit;
        }

        $this->async($find['pay_orderid'],'SUCCESS');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}